package com.zx.onlineeducation.service.edu.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zx.onlineeducation.service.edu.entity.SubjectDO;
import com.zx.onlineeducation.service.edu.entity.excel.SubjectData;
import com.zx.onlineeducation.service.edu.entity.vo.SubjectQueryVO;
import com.zx.onlineeducation.service.edu.entity.vo.SubjectTreeVO;
import com.zx.onlineeducation.service.edu.listener.SubjectDataListener;
import com.zx.onlineeducation.service.edu.mapper.SubjectMapper;
import com.zx.onlineeducation.service.edu.service.SubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * <p>
 * 课程分类 服务实现类
 * </p>
 *
 * @author 郑雪
 * @since 2022-01-12
 */
@Service
public class SubjectServiceImpl extends ServiceImpl<SubjectMapper, SubjectDO> implements SubjectService {

    /**
     * 添加课程分类，通过上传的Excel文件批量添加数据
     *
     * @param file 上传的Excel文件 {@link MultipartFile}
     * @author 郑雪
     * @since 2022-01-12
     */
    @Override
    public void save(MultipartFile file) {
        try {
            // 获取文件的输入流
            InputStream inputStream = file.getInputStream();

            // 用EasyExcel读取文件
            EasyExcel.read(inputStream, SubjectData.class, new SubjectDataListener(this)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取课程分类树形结构数据列表
     *
     * @param  subjectQueryVO 课程分类查询对象 {@link SubjectQueryVO}
     * @return 携带SubjectTreeVO对象的List集合 {@link SubjectTreeVO}
     * @author 郑雪
     * @since 2022-01-12
     */
    @Override
    public List<SubjectTreeVO> getTree(SubjectQueryVO subjectQueryVO) {

        // 返回结果
        List<SubjectTreeVO> result = new ArrayList<>();

        // 创建条件查询对象
        QueryWrapper<SubjectDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("parent_id");
        queryWrapper.orderByAsc("sort");

        // 查询所有课程分类列表
        List<SubjectDO> list = this.list(queryWrapper);

        // 定义一个Map，方便遍历
        Map<String, SubjectTreeVO> map = new HashMap<>();

        // 遍历，给Map赋值
        for (SubjectDO subjectDO : list) {
            SubjectTreeVO subjectTreeVO = new SubjectTreeVO();
            BeanUtils.copyProperties(subjectDO, subjectTreeVO);
            map.put(subjectTreeVO.getId(), subjectTreeVO);
        }

        // 课程分类名称，模糊查询
        String title = subjectQueryVO.getTitle();

        // 遍历，给result赋值
        for (SubjectDO subjectDO : list) {
            String id = subjectDO.getId();
            String parentId = subjectDO.getParentId();
            SubjectTreeVO subjectTreeVO = map.get(id);
            String originTitle = subjectTreeVO.getTitle();
            String myTitle = originTitle.toLowerCase();

            if (!StringUtils.isEmpty(title)) {
                title = title.toLowerCase();
                if (myTitle.contains(title)) {
                    subjectTreeVO.setMatch(true);
                    int startIndex = myTitle.indexOf(title);
                    int endIndex = startIndex + title.length();
                    String matchHtml = originTitle.substring(0, startIndex)
                            + "<span style='color:#F56C6C;'>" + originTitle.substring(startIndex, endIndex) + "</span>"
                            + originTitle.substring(endIndex);
                    subjectTreeVO.setMatchHtml(matchHtml);
                }
            }

            // 如果是一级分类
            if ("0".equals(parentId)) {
                if((StringUtils.isEmpty(title) || subjectTreeVO.getMatch())) {
                    result.add(subjectTreeVO);
                    if (subjectTreeVO.getMatchHtml() == null) {
                        subjectTreeVO.setMatch(false);
                    }
                }
            }
            // 如果不是一级分类
            else {
                // 获取它的上级分类
                SubjectTreeVO parentSubjectTreeVO = map.get(parentId);
                // 获取下级集合
                List<SubjectTreeVO> children = parentSubjectTreeVO.getChildren();

                if(StringUtils.isEmpty(title) || subjectTreeVO.getMatch()) {
                    if (!result.contains(parentSubjectTreeVO)) {
                        parentSubjectTreeVO.setMatch(true);
                    }
                    if (children == null) {
                        children = new ArrayList<>();
                        parentSubjectTreeVO.setChildren(children);
                    }
                    // 添加下级分类
                    children.add(subjectTreeVO);
                }

            }
        }

        return result;
    }

    /**
     * 删除课程分类及其下级分类
     *
     * @return 成功 true ，失败 false
     * @param id 课程分类ID
     * @author 郑雪
     * @since 2022-01-13
     */
    @Override
    public boolean remove(String id) {
        QueryWrapper<SubjectDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", id);
        queryWrapper.or();
        queryWrapper.eq("parent_id", id);
        return this.remove(queryWrapper);
    }

    /**
     * 获取一级课程分类列表
     *
     * @return SubjectDO对象的List集合 ${@link SubjectDO}
     * @author 郑雪
     * @since 2022-01-13
     */
    @Override
    public List<SubjectDO> getOneLevel() {
        QueryWrapper<SubjectDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", "0");
        queryWrapper.orderByAsc("sort");
        return this.list(queryWrapper);
    }

    /**
     * 获取二级课程分类列表
     *
     * @param  parentId 一级课程分类ID
     * @return SubjectDO对象的List集合 ${@link SubjectDO}
     * @author 郑雪
     * @since 2022-01-13
     */
    @Override
    public List<SubjectDO> getTwoLevel(String parentId) {
        QueryWrapper<SubjectDO> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("parent_id", parentId);
        queryWrapper.orderByAsc("sort");
        return this.list(queryWrapper);
    }
}
